package top.xana.acg.anime.ui.page

import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator
import top.xana.acg.anime.R
import top.xana.acg.anime.SearchSource
import top.xana.acg.anime.databinding.SearchFragmentBinding
import top.xana.acg.anime.ui.fragment.SearchListFragment
import top.xana.acg.anime.utils.cast
import top.xana.acg.base.BaseFragment
import top.xana.acg.base.ViewPager2Adapter

class SearchFragment : BaseFragment<SearchFragmentBinding>(R.layout.search_fragment) {

    companion object {
        fun newInstance() = SearchFragment()
        const val TAG = "SearchFragment"
    }

    private lateinit var fragemnts: List<Fragment>

    override fun initView() = with(binding) {
        super.initView()
        setTabViewPager()
        viewPager2.registerOnPageChangeCallback(pagerCallback)
        val searchRef = fragemnts[viewPager2.currentItem].cast<OnSearchListener>() ?: return@with
        searchView.setSearchPtr(searchRef::onSearch)
    }

    private val pagerCallback = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            val kw = binding.searchView.kw
            if (kw.isEmpty()) return
            super.onPageSelected(position)
            val onSearchListener =
                fragemnts[binding.viewPager2.currentItem].cast<OnSearchListener>()
            onSearchListener?.onSearch(kw)
        }
    }

    private fun setTabViewPager() = with(binding) {
        val arr = resources.getStringArray(R.array.searchTab)
        fragemnts = arr.mapIndexed { i, _ ->
            SearchListFragment.newInstance(SearchSource.values()[i])
        }
        viewPager2.adapter = ViewPager2Adapter(
            fragemnts,
            childFragmentManager,
            lifecycle
        )
        TabLayoutMediator(tabLayout, viewPager2) { tab, i ->
            tab.text = arr[i]
        }.attach()
    }

    override fun onDestroyView() {
        binding.viewPager2.unregisterOnPageChangeCallback(pagerCallback)
        super.onDestroyView()
    }

    interface OnSearchListener {
        fun onSearch(kw: String)
    }
}
